<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Category as CategoryModel;

/**
 * 分类控制器
 * @package app\user\admin
 */
class Category extends Admin
{
    /**
     * 消息列表
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data_list = CategoryModel::where($this->getMap())->where('pid','=',0)
            ->order($this->getOrder('id DESC'))
            ->paginate();

        $child_btn=[
            'title' => 'sub category',
            'href'  => url('child', ['id' => '__id__']),
            'icon'  => 'fa fa-fw fa-chevron-down'
        ];
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('category')
            ->addTopButton('add',['title'=>'Add'])
            ->addRightButton('custom',$child_btn)
            ->addRightButton('edit',['title'=>'edit'])
            ->addRightButton('delete',['title'=>'delete','data-confirm'=>'confirm','data-cancel'=>'cancel','data-title'=>'Warning! After deleting data, merchants associated with that data will need to reset the category data, sure you want to continue?'])
            ->addColumns([
                ['id', 'ID'],
                ['name', 'Category'],
                ['icon', 'Icon','picture'],
                ['select_icon', 'Selected Icon','picture'],
                ['update_user', 'Updater'],
                ['update_time', 'Last update time'],
                ['right_button', 'Operation', 'btn'],
            ])
            ->setRowList($data_list)
            ->setSearch(['name'=>'Category'])
            ->fetch();
    }

    /**
     * 新增
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add($pid=0)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $data['name'] == '' && $this->error('Please fill in the category name');
            mb_strlen($data['name'])>30 && $this->error('Category can input up to 15 characters');
            if(!$pid){
                $data['icon'] == '' && $this->error('Please upload icon');
                $data['select_icon'] == '' && $this->error('Please upload selected icon');
            }
            if(!$this->check($data['name'],0,$pid)) $this->error('Data duplicated, please re-enter');
            $list = [];
            $list['name']=$data['name'];
            if(!$pid){
                $list['icon']=$data['icon'];
                $list['select_icon']=$data['select_icon'];
            }
            $list['update_time']=date('Y-m-d H:i:s');
            $list['create_time']=date('Y-m-d H:i:s');
            $list['update_user']=session('user_auth')['username'];
            $list['pid']=$pid;
            $categoryModel = new CategoryModel();
            $url=$pid?url('child', ['id' =>$pid]):'index';
            if (false !== $categoryModel->save($list)) {
                $this->success('add success', $url);
            } else {
                $this->error('add failed');
            }
        }

        $form=ZBuilder::make('form')->addFormItems([
            ['text', 'name', 'Category']
        ]);
        if(!$pid){
            $form=$form->addFormItems([
                ['image', 'icon', 'Icon'],
                ['image', 'select_icon', 'Selected Icon'],
            ]);
        }

        return $form->fetch();
    }

    public function edit($id = 0,$pid=0)
    {
        if ($id === 0) $this->error('missing parameter');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            //$data['status']=='on'?$data['status']=1:$data['status']=0;
            // 验证
            $data['name'] == '' && $this->error('Please fill in the category name');
            mb_strlen($data['name'])>30 && $this->error('Category can input up to 15 characters');
            if(!$pid){
                $data['icon'] == '' && $this->error('Please upload icon');
                $data['select_icon'] == '' && $this->error('Please upload selected icon');
            }
            if(!$this->check($data['name'],$id,$pid)) $this->error('Data duplicated, please re-enter');
            $data['update_time']=date('Y-m-d H:i:s');
            $data['update_user']=session('user_auth')['username'];
            $data['pid']=$pid;
            $url=$pid?url('child', ['id' =>$pid]):'index';
            if (CategoryModel::update($data,['id'=>$id])) {
                $this->success('edit success', $url);
            } else {
                $this->error('edit failed');
            }
        }
        // 获取数据
        $info = CategoryModel::get($id);

        // 使用ZBuilder快速创建表单
        $form=ZBuilder::make('form')->addFormItems([
            ['text', 'name', 'Category'],
        ]);
        if(!$pid){
            $form=$form->addFormItems([
                ['image', 'icon', 'Icon'],
                ['image', 'select_icon', 'Selected Icon'],
            ]);
        }
        return $form->setFormData($info)->fetch();
    }

    public function child($id = 0)
    {
        if ($id === 0) $this->error('missing parameter');
        $data_list = CategoryModel::where($this->getMap())->where('pid','=',$id)
            ->order($this->getOrder('id DESC'))
            ->paginate();

        $btn_access = [
            'title' => 'back',
            'icon'  => 'fa fa-fw fa-chevron-left',
            'href'  => url('index')
        ];

        return ZBuilder::make('table')
            ->setTableName('category')
            ->hideCheckbox()
            ->addTopButton('add',['title'=>'add','href'=>url('add', ['pid' => $id])])
            ->addTopButton('custom',$btn_access)
            ->addRightButton('edit',['title'=>'edit','href'=>url('edit', ['pid' => $id,'id'=>'__id__'])])
            ->addRightButton('delete',['title'=>'delete','data-confirm'=>'confirm','data-cancel'=>'cancel','href'=>url('delete', ['pid' => $id,'ids'=>'__id__']),'data-title'=>'Warning! After deleting data, merchants associated with that data will need to reset the category data, sure you want to continue?'])
            ->addColumns([
                ['id', 'ID'],
                ['name', 'Category'],
                ['update_user', 'Updater'],
                ['update_time', 'Last update time'],
                ['right_button', 'Operation', 'btn'],
            ])
            ->setRowList($data_list)
            ->setSearch(['name'=>'category'])
            ->fetch();
    }

    public function delete($record = [],$pid=0)
    {
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $categoryModel = new CategoryModel();
        $categoryModel->deleteAll($ids);
        $url=$pid?url('child', ['id' =>$pid]):'index';
        $this->success('delete success',$url);
    }

    private function check($name,$id=0,$pid=0){
        $id=CategoryModel::where(['name'=>trim($name)])
            ->when($id,function ($query)use($id){
                $query->where('id','neq',$id);
            })
            ->when($pid,function ($query)use ($pid){
                $query->where('pid','eq',$pid);
            })
            ->value('id');
        if($id){
            return false;
        }else{
            return true;
        }
    }
}
